package com.flow.framework.config.service.system.health.impl;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;

/**
 * nacos配置中心健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/5
 */
@Slf4j
@RequiredArgsConstructor
public class NacosConfigHealthCheckServiceImpl implements IHealthCheckService {

    private static final String UP_STATUS_STRING = "UP";

    private final NacosConfigManager nacosConfigManager;

    @Override
    public List<ServiceHealthVo> check() {
        try {
            ConfigService configService = nacosConfigManager.getConfigService();
            String status = configService.getServerStatus();
            if (!UP_STATUS_STRING.equalsIgnoreCase(status)) {
                log.error("nacos config server status error. status : {}", status);
                return Collections.singletonList(SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_CONFIG_CENTER_CODE,
                        "nacos " + status, null));
            }
            return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_CONFIG_CENTER_CODE));
        } catch (Exception e) {
            log.error("check nacos config error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_CONFIG_CENTER_CODE, e.getMessage(), null)
            );
        }
    }
}
